package com.example.applearrow.activityresult;

import com.example.applearrow.activityresult.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class ActivityA extends Activity {
    
    // Actions requested from this activity
    public final static int GET_SOMETHING = 1;

    private static final String TAG = "MainActivity";
    
    EditText mEditText;
    TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        mEditText = (EditText) findViewById(R.id.editText);
        mTextView = (TextView) findViewById(R.id.testResult);
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG,"onResume");
    }

    public void onButtonClick(View v){
        Intent intent = new Intent(this, ActivityB.class);
        final String value = mEditText.getText().toString();
        if( !value.equals("") ){
            intent.putExtra(ActivityB.INPUT_VALUE,value);
        }
        startActivityForResult(intent, GET_SOMETHING);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    /**
     * Note that {@link onActivityResult()} will be called before {@link onResume()}
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == GET_SOMETHING) {
            if(resultCode == RESULT_OK){
                Log.d(TAG,"onActivityResult RESULT_OK");
                String result = data.getStringExtra(ActivityB.RESULT);
                StringBuilder sb = new StringBuilder();
                sb.append(getString(R.string.result_ok));
                sb.append("\n");
                sb.append(getString(R.string.received));
                sb.append(result);
                mTextView.setText(sb.toString());
            }
            if (resultCode == RESULT_CANCELED) {
                Log.d(TAG,"onActivityResult RESULT_CANCELED");
                mTextView.setText(getString(R.string.result_cancel));
            }
        }
    }

}
